/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

MainPanel = function(){
    this.preview = new Ext.Panel({
        id: 'preview',
        region: 'south',
        cls:'preview',
        autoScroll: true,
        listeners: FeedViewer.LinkInterceptor,

        tbar: [{
            id:'tab',
            text: 'Просмотр',
            iconCls: 'new-tab',
            disabled:true,
            handler : this.openTab,
            scope: this
        },
        '-',
		{
            id:'itab',
            text: 'Открыть источник',
            iconCls: 'new-tab',
            disabled:true,
            handler : this.openTabIframe,
            scope: this
        }
        ,
		'-',
        {
            id:'win',
            text: 'Открыть в новом окне',
            iconCls: 'new-win',
            disabled:true,
            scope: this,
            handler : function(){
                window.open(this.gsm.getSelected().data.link);
            }
        }
		],

        clear: function(){
            this.body.update('');
            var items = this.topToolbar.items;
            items.get('tab').disable();
            items.get('win').disable();
			items.get('itab').disable();
        }
    });

	var cp = new Ext.state.CookieProvider();
	var sen = cp.get("sen",false);
    this.grid = new FeedGrid(this, {
        tbar:[
		{
            text:'Обновить',
            iconCls: 'refresh-icon',
            handler: this.RefreshFeed,
            scope:this
        },
		'-',
		{
            text:'Все прочитаны',
            tooltip: {title:'Отметить все прочитанными',text:'Отметить все посты, как прочитанные.'},
            iconCls: 'tabs',
            handler: this.AllRead,
            scope:this
        },
		/* '-',
		{
            text:'Открыть все',
            tooltip: {title:'Открыть все',text:'Открыть все посты в новых вкладках'},
            iconCls: 'tabs',
            handler: this.openAll,
            scope:this
        }, */
        '-',
        {
            split:true,
            text:'Вид',
            tooltip: {title:'Вид',text:'Измените расположение окон.'},
            iconCls: 'preview-bottom',
            handler: this.movePreview.createDelegate(this, []),
            menu:{
                id:'reading-menu',
                cls:'reading-menu',
                width:100,
                items: [{
                    text:'Внизу',
                    checked:false,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-bottom'
                },{
                    text:'Справа',
                    checked:false,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-right'
                },{
                    text:'Скрыть',
                    checked:true,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-hide'
                }]
            }
        }
        ]
    });

    MainPanel.superclass.constructor.call(this, {
        id:'main-tabs',
        activeTab:0,
        region:'center',
        margins:'0 5 5 0',
        resizeTabs:true,
        tabWidth:150,
        minTabWidth: 120,
        enableTabScroll: true,
        plugins: new Ext.ux.TabCloseMenu(),
        items: {
            id:'main-view',
            layout:'border',
            title:'Загрузка...',
            hideMode:'offsets',
            items:[
                this.grid, {
                id:'bottom-preview',
                layout:'fit',
                items:this.preview,
                height: 250,
                split: true,
                border:false,
                region:'south',
				hidden:true
            }, {
                id:'right-preview',
                layout:'fit',
                border:false,
                region:'east',
                width:350,
                split: true,
                hidden:true
            }]
        }
    });
	//this.grid.togglePreview(sen);
    this.gsm = this.grid.getSelectionModel();

    this.gsm.on('rowselect', function(sm, index, record){
		
        FeedViewer.getTemplate().overwrite(this.preview.body, record.data);
        var items = this.preview.topToolbar.items;
        items.get('tab').enable();
        items.get('win').enable();
		items.get('itab').enable();
    }, this, {buffer:250});
	
	this.grid.on('rowclick', function(grid, index, e){
		var oldTitle = grid.getView().getRow(index).getElementsByTagName("div")[1].innerHTML;
		var newTitle = oldTitle.replace("<b>","");
			newTitle = newTitle.replace("</b>","");
		grid.getView().getRow(index).getElementsByTagName("div")[1].innerHTML = newTitle;
		grid.store.getAt(index).data.hasread=true;
	});
    this.grid.store.on('beforeload', this.preview.clear, this.preview);
    //this.grid.store.on('load', this.gsm.selectFirstRow, this.gsm);
  	this.grid.store.on('load', function(store) {
		//store.setDefaultSort('pubDate', "DESC");
		//alert("Load");
		var url = store.baseParams.feed;
		var cp = new Ext.state.CookieProvider();
		var ftimes = Ext.util.JSON.decode(cp.get("feedviewtimes","{}"));
		var ldate = (new Date()).getTime();
		if (store.getAt(0)) {
			ldate = new Date(store.getAt(0).data.pubDate).getTime();
			ldate = ldate.toString().substring(0,ldate.toString().length-3);
			if (!parseInt(ldate) || parseInt(ldate)==0) {
				ldate = (new Date()).getTime();
				ldate = ldate.toString().substring(0,ldate.toString().length-3);
			}
		}	
		ftimes[url] = ldate;
		cp.set("feedviewtimes",Ext.util.JSON.encode(ftimes));
		//this.render();
	});  

    //this.grid.on('rowdblclick', this.openTab, this);
};

function ShowIframe(record,container){
	record = (record && record.data) ? record : this.gsm.getSelected();
        var d = record.data;
        var id = !d.link ? Ext.id() : d.link.replace(/[^A-Z0-9-_]/gi, '');
        var tab;
        if(!(tab = container.getItem(id))){
            tab = new Ext.Panel({
                id: id,
                cls:'preview single-preview',
                title: d.title,
                tabTip: d.title,
                html: FeedViewer.getTemplateIframe().apply(d),
                closable:true,
                listeners: FeedViewer.LinkInterceptor,
                autoScroll:false,
                border:true,

                tbar: [
					{
                    text: 'Обновить',
                    iconCls: 'new-win',
                    handler : function(){
                        var fr = document.getElementById(id).parentNode.getElementsByTagName("iframe")[0];
						fr.src = fr.src;
						//.location.reload();
                    }},{
                    text: 'Открыть в новом окне',
                    iconCls: 'new-win',
                    handler : function(){
                        window.open(d.link);
                    }}
					]
            });
            container.add(tab);
        }else{
			FeedViewer.getTemplateIframe().overwrite(tab.body, d);
		}
        container.setActiveTab(tab);
}

Ext.extend(MainPanel, Ext.TabPanel, {

    loadFeed : function(feed){
        this.grid.loadFeed(feed.url);
        Ext.getCmp('main-view').setTitle(feed.text);
		Ext.getCmp('main-view').show();
		try {
		pageTracker._trackPageview("/feed?url="+feed.url);
		} catch(err) {}
    },
	
	RefreshFeed : function(){
		var feed = this.grid.store.baseParams.feed;
		this.grid.RefreshFeed(feed);
		try {
		pageTracker._trackPageview("/refresh_feed?url="+feed);
		} catch(err) {}
    },

    movePreview : function(m, pressed){
        if(!m){ // cycle if not a menu item click
            var readMenu = Ext.menu.MenuMgr.get('reading-menu');
            readMenu.render();
            var items = readMenu.items.items;
            var b = items[0], r = items[1], h = items[2];
            if(b.checked){
                r.setChecked(true);
            }else if(r.checked){
                h.setChecked(true);
            }else if(h.checked){
                b.setChecked(true);
            }
            return;
        }
        if(pressed){
            var preview = this.preview;
            var right = Ext.getCmp('right-preview');
            var bot = Ext.getCmp('bottom-preview');
            var btn = this.grid.getTopToolbar().items.get(2);
            switch(m.text){
                case 'Внизу':
                    right.hide();
                    bot.add(preview);
                    bot.show();
                    bot.ownerCt.doLayout();
                    btn.setIconClass('preview-bottom');
					this.grid.view.showPreview=true;
                    break;
                case 'Справа':
                    bot.hide();
                    right.add(preview);
                    right.show();
                    right.ownerCt.doLayout();
                    btn.setIconClass('preview-right');
					this.grid.view.showPreview=true;
                    break;
                case 'Скрыть':
                    preview.ownerCt.hide();
                    preview.ownerCt.ownerCt.doLayout();
                    btn.setIconClass('preview-hide');
					this.grid.view.showPreview=false;
                    break;
            }
        }
    },

    openTab : function(record){
        record = (record && record.data) ? record : this.gsm.getSelected();
        var d = record.data;
        var id = !d.link ? Ext.id() : d.link.replace(/[^A-Z0-9-_]/gi, '');
        var tab;
		var cont = this;
        if(!(tab = this.getItem(id))){
            tab = new Ext.Panel({
                id: id,
                cls:'preview single-preview',
                title: d.title,
                tabTip: d.title,
                html: FeedViewer.getTemplate().apply(d),
                closable:true,
                listeners: FeedViewer.LinkInterceptor,
                autoScroll:true,
                border:true,

                tbar: [
				{
                    text: 'Открыть',
                    iconCls: 'new-win',
                    handler : function() {ShowIframe(record,cont)}
                },'-',
				{
                    text: 'Открыть в новом окне',
                    iconCls: 'new-win',
                    handler : function(){
                        window.open(d.link);
                    }
                }]
            });
            this.add(tab);
        }
        this.setActiveTab(tab);
    },
	openTabGetCode : function(){
        var id = "get-code";
        var tab;
				var cont = this;
        if(!(tab = this.getItem(id))){
            tab = new GetCode();
            this.add(tab);
        }
        this.setActiveTab(tab);
    },
	openTabIframe : function(record){
        record = (record && record.data) ? record : this.gsm.getSelected();
        var d = record.data;
        var id = !d.link ? Ext.id() : d.link.replace(/[^A-Z0-9-_]/gi, '');
        var tab;
        if(!(tab = this.getItem(id))){
            tab = new Ext.Panel({
                id: id+"_iframe",
                cls:'preview single-preview',
                title: d.title,
                tabTip: d.title,
                html: FeedViewer.getTemplateIframe().apply(d),
                closable:true,
                listeners: FeedViewer.LinkInterceptor,
                autoScroll:false,
                border:true,

                tbar: [
					{
                    text: 'Обновить',
                    iconCls: 'new-win',
                    handler : function(){
                        var fr = document.getElementById(id).parentNode.getElementsByTagName("iframe")[0];
						//fr.src = fr.src;
						fr.contentDocument.location.reload(true);
						//.location.reload();
                    }},{
                    text: 'Открыть в новом окне',
                    iconCls: 'new-win',
                    handler : function(){
                        window.open(d.link);
                    }}
					]
            });
            this.add(tab);
        }else{"active"}
        this.setActiveTab(tab);
    },
	AllRead : function(){
        this.beginUpdate();
        this.grid.store.data.each(function(record) {record.data.hasread=true;}, this);
		this.grid.getView().refresh();
		//var oldTitle = grid.getView().getRow(index).getElementsByTagName("div")[1].innerHTML;
		//var newTitle = oldTitle.replace("<b>","");
		//	newTitle = newTitle.replace("</b>","");
		//grid.getView().getRow(index).getElementsByTagName("div")[1].innerHTML = newTitle;
		
        this.endUpdate();
    },
    openAll : function(){
        this.beginUpdate();
        this.grid.store.data.each(this.openTab, this);
        this.endUpdate();
    },
	createButton : function (value, contentid, attrs,record) {
            new Ext.Button({text: value, iconCls: 'new-win',style:'padding-left:10px;',handler : function(btn, e) {
						if (attrs.type==1) {
							FeedViewer.getMainPanel.openTabIframe(record);
						}else{
							window.open(record.data.link);;
						}
                    }}).render(document.body, contentid);
        }
});